//
//  SureSafeWordController.m
//  SafPay
//
//  Created by 贺庆博 on 2018/6/19.
//  Copyright © 2018年 ebo. All rights reserved.
//

#import "SureSafeWordController.h"
#import "SafWordCell.h"
#import "HomeViewController.h"
#import "SettingViewController.h"
@interface SureSafeWordController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong,nonatomic) UIView *mainView;
@property (strong,nonatomic) UICollectionView *myCollectionView;
@property (strong,nonatomic) UICollectionView *handleCollectionView;
@property (strong,nonatomic) NSMutableArray *arrDS;
@property (strong,nonatomic) NSMutableArray *selectArr;

@end

@implementation SureSafeWordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"备份助记词";
    [self initNav];
    [self initUI];
    // Do any additional setup after loading the view from its nib.
}

- (UIView *)mainView
{
    if (!_mainView) {
        _mainView = [[UIView alloc]initWithFrame:CGRectMake(12, 12, kScreenWidth - 24, 268)];
        __weak typeof (UIView *)weakMain = _mainView;
        _mainView.backgroundColor = [UIColor whiteColor];
        UILabel *titleLab = [UILabel labelWithFont:kFONT(16) color:rgb(58,58,58) text:@"抄写下你的钱包助记词"];
        titleLab.textAlignment = NSTextAlignmentCenter;
        UILabel *subLab = [UILabel labelWithFont:kFONT(13) color:rgb(159,159,159) text:@"请按顺序点击助记词，以确认你的备份助记词正确。"];
        subLab.textAlignment = NSTextAlignmentCenter;
        [_mainView addSubview:titleLab];
        [_mainView addSubview:subLab];
        [_mainView addSubview:self.myCollectionView];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakMain);
            make.top.mas_equalTo(27);
        }];
        [subLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakMain);
            make.top.mas_equalTo(titleLab.mas_bottom).mas_offset(13);
        }];
        [self.myCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(subLab.mas_bottom).mas_offset(21);
            make.centerX.equalTo(weakMain);
            make.height.equalTo(@142);
            make.width.equalTo(@298);
        }];
    }
    return _mainView;
}
-(UICollectionView *)myCollectionView{
    if(!_myCollectionView){
        
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置每个item的大小为100*100
        layout.itemSize = CGSizeMake(53, 27);
        //创建collectionView 通过一个布局策略layout来创建
        _myCollectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
        //代理设置
        _myCollectionView.layer.cornerRadius = 8;
        _myCollectionView.layer.borderColor = rgb(186,186,186).CGColor;
        _myCollectionView.layer.borderWidth = 1;
        _myCollectionView.delegate=self;
        _myCollectionView.dataSource=self;
        //注册item类型 这里使用系统的类型
        [_myCollectionView registerNib:[UINib nibWithNibName:@"SafWordCell" bundle:nil] forCellWithReuseIdentifier:@"SafWordCell"];
        [_myCollectionView setBackgroundColor:[UIColor clearColor]];
        [_myCollectionView setScrollEnabled:NO];
        
    }
    return _myCollectionView;
}

-(UICollectionView *)handleCollectionView{
    if(!_handleCollectionView){
        
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置每个item的大小为100*100
        layout.itemSize = CGSizeMake(53, 27);
        //创建collectionView 通过一个布局策略layout来创建
        _handleCollectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
        //代理设置
        _handleCollectionView.delegate=self;
        _handleCollectionView.dataSource=self;
        //注册item类型 这里使用系统的类型
        [_handleCollectionView registerNib:[UINib nibWithNibName:@"SafWordCell" bundle:nil] forCellWithReuseIdentifier:@"SafWordCell"];
        [_handleCollectionView setBackgroundColor:[UIColor clearColor]];
        [_handleCollectionView setScrollEnabled:NO];
        
    }
    return _handleCollectionView;
}

- (NSMutableArray *)arrDS
{
    if (!_arrDS) {
        _arrDS = [NSMutableArray array];
     
    }
    return _arrDS;
}
- (NSMutableArray *)selectArr
{
    if (!_selectArr) {
        _selectArr = [NSMutableArray array];
    }
    return _selectArr;
}
- (void)initNav
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 30);
    [btn setTitle:@"跳过" forState:UIControlStateNormal];
    btn.titleLabel.font = kFONT(15);
    [btn addTarget:self action:@selector(skipClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
}
- (void)initUI
{
    
    for (int i = 0; i < 12; i ++) {
        SafeWordModel *model = [SafeWordModel new];
        model.word = [self.sureKeyWord objectAtIndex:i];
        [self.arrDS addObject:model];
    }
    self.arrDS=(NSMutableArray *)[self gk_randomArray:self.arrDS];

    [self.view addSubview:self.mainView];
    [self.view addSubview:self.handleCollectionView];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"下一步" forState:UIControlStateNormal];
    btn.titleLabel.font = kFONT(16);
    btn.backgroundColor = rgb(33,177,227);
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.equalTo(@44);
    }];
    
    [self.handleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(btn.mas_top).mas_offset(-20);
        make.centerX.equalTo(self.view);
        make.height.equalTo(@142);
        make.width.equalTo(@298);
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 *  @brief 将数组随机打乱
 */
- (NSArray *)gk_randomArray:(NSMutableArray *)oldArr {
    // 转为可变数组
    NSMutableArray * tmp = oldArr;
    // 获取数组长度
    NSInteger count = tmp.count;
    // 开始循环
    while (count > 0) {
        // 获取随机角标
        NSInteger index = arc4random_uniform((int)(count - 1));
        // 获取角标对应的值
        id value = tmp[index];
        // 交换数组元素位置
        tmp[index] = tmp[count - 1];
        tmp[count - 1] = value;
        count--;
    }
    // 返回打乱顺序之后的数组
    return tmp.copy;
}




-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.handleCollectionView) {
        return self.arrDS.count?:12;
    }
    return self.selectArr.count;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
/** cell的内容*/
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SafWordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SafWordCell" forIndexPath:indexPath];
    if (collectionView == _myCollectionView) {
        cell.canEdit = NO;
        cell.model = self.selectArr[indexPath.row];
    }else
    {
        cell.canEdit = YES;
        cell.model = self.arrDS[indexPath.row];
    }
    cell.idx = indexPath.row;
    cell.wordBtnBlock = ^(UIButton *btn, NSInteger idx) {
        if (collectionView == self->_myCollectionView) {
            return ;
        }
        SafeWordModel *selectModel = self.arrDS[idx];
        selectModel.isSelected = !selectModel.isSelected;
        [self.handleCollectionView reloadData];
        if (selectModel.isSelected == YES) {
            [self.selectArr addObject:selectModel];
        }else
        {
            [self.selectArr removeObject:selectModel];
        }
        [self.myCollectionView reloadData];
    };
    return cell;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(21, 17, 10, 17);//分别为上、左、下、右
}
- (void)btnClick
{
    if(self.selectArr.count==12){
        
       
        
        //NSString *str=[WalletStatusModel getWalletKeyWord];
        NSString *str=[AccountTools shared].currentAccount.keyWord;
        NSArray *arr=[str componentsSeparatedByString:@","];
        if(arr.count!=0){
            __block BOOL Status=YES;
            [arr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                SafeWordModel *model=[self.selectArr objectAtIndex:idx];
                if(![obj isEqualToString:model.word]){
                    
                    Status=NO;
                }
                
            }];
            if(Status){
                
                
//                [WalletStatusModel saveWalletKeyWord:str];
                [AccountTools shared].currentAccount.keyWord=str;
                [AccountTools shared].currentAccount.isCopy=YES;
                [[AccountTools shared]updateUserInfo:[AccountTools shared].currentAccount];
               
                if(self.isHome){
                    
                    [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        if([obj isKindOfClass:[HomeViewController class]]){
                            
                            [self.navigationController popToViewController:obj animated:YES];
                            
                        }
                    }];
                }else if (self.isSetting){
                    
                    [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        if([obj isKindOfClass:[SettingViewController class]]){
                            
                            [self.navigationController popToViewController:obj animated:YES];
                            
                        }
                    }];
                }
                else{
                    
                     HomeViewController *vc = [HomeViewController new];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
            else{
                

                [AccountTools shared].currentAccount.isCopy=NO;
                [[AccountTools shared]updateUserInfo:[AccountTools shared].currentAccount];
                [self.selectArr removeAllObjects];

                [self.arrDS enumerateObjectsUsingBlock:^(SafeWordModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.isSelected=!obj.isSelected;
                }];
                [self.myCollectionView reloadData];
                [self.handleCollectionView reloadData];
                [MBProgressHUD showErrorWithText:@"助记词错误"];
            }
        }
    }
}
-(void)skipClick{
    
//    [WalletStatusModel saveWalletKeyWord:@"NO"];
    [AccountTools shared].currentAccount.isCopy=NO;
    [[AccountTools shared]updateUserInfo:[AccountTools shared].currentAccount];
    
    if(self.isHome){
        
        [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
            if([obj isKindOfClass:[HomeViewController class]]){
                
                 [self.navigationController popToViewController:obj animated:YES];
                
            }
        }];
       
    }else if (self.isSetting){
        
        [self.navigationController.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if([obj isKindOfClass:[SettingViewController class]]){
                
                [self.navigationController popToViewController:obj animated:YES];
                
            }
        }];
    }
    else{
        
        HomeViewController *vc = [HomeViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
@end
